//  引入数据库模型
var { customersModel } = require('../models/customersModels');

// -- ----------- 严晴---------- --

//  新增学生
module.exports.customersDao = async (customers) => await customersModel.create(customers);

//  获取销售员客户
module.exports.getSalesToCustomersDao = async (data) => {
    var total = await customersModel.countDocuments({ delete: false, belongToSales: data.belongToSales });
    var pages = Math.ceil(total / data.pageSize);
    // console.log('333', data.belongToSales);
    var customers = await customersModel
        .find({ delete: false, belongToSales: data.belongToSales })
        .populate('belongToSales')
        .limit(data.pageSize - 0)  //  设置请求数据的条数
        .skip((data.currentPage - 1) * data.pageSize);  //  设置跳过请求的条数
    return {
        total, pages, customers
    }
};

//  伪删除客户
module.exports.delSalesToCustomersDao = async (_id) => await customersModel.updateOne({ _id }, { delete: true });

//  获取要修改的客户的信息
module.exports.getModifyCustomersDao = async (_id) => await customersModel.find({ _id });

//  确认修改客户
module.exports.modifyCustomersDao = async ({ _id, name, age, gender, phone }) => await customersModel.updateOne({ _id }, { name, age, gender, phone });



//  获取管理员页面的客户
module.exports.getCustomersDao = async (data) => {
    var total = await customersModel.countDocuments({ delete: false });
    var pages = Math.ceil(total / data.pageSize);

    // var data = await customersModel.aggregate([
    //     {
    //         $lookup: {
    //             from: 'sales',
    //             localField: '_id',
    //             foreignField: 'belongToSales',
    //             as: 'salesData'
    //         }

    //     },
    //     {
    //         //  条件查询
    //         $match: {
    //             delete: false   //  查询的条件 这里是只查询
    //         }
    //     }
    // ])

    var customers = await customersModel
        .aggregate([
            {
                $lookup: {
                    from: 'sales',
                    localField: 'belongToSales',
                    foreignField: '_id',
                    as: 'salesData'
                }

            },
            {
                //  条件查询
                $match: {
                    delete: false   //  查询的条件 这里是只查询
                }
            },
            {
                $skip: (data.currentPage - 1) * data.pageSize  //  设置跳过请求的条数
            },
            {
                $limit: data.pageSize - 0  //  设置请求数据的条数
            }
        ])
    return {
        total, pages, customers
    }
};

// 获取所有客户
module.exports.getCustomersAllId = async (data) => {
    return await customersModel.find(data)
};